/**
 * theme：拍照控件
 *author：杨波
 * date：2018-11-12
 * versions：1.0.0
 */
;(function ($) {
    var formmatterData = {
        id: 'fileId',
        name: 'fileName',
        thumb: 'thumbUrl',
        download: 'htmlUrl'
    },
    formmatterUpload = {
        id: 'mid',
        name: 'fileName',
        thumb: 'thumbUrl',
        download: 'htmlUrl'
    };

    //初始化入口
    function init(container){
        var state = $.data(container, 'photographic');
        createDialog(state.options);
        $(container).click(function () {
            state.options.dialog.css("display","block");
        });
    }

    //创建拍照窗口
    function createDialog(options){
        var zIndex = getMaxZIndex();
        var str = '<div class="photographic_mask" style="z-index: ' + zIndex + '">\n' +
            '    <div class="photographic_left">\n' +
            '        <div class="photographic_left_cancel"></div>\n' +
            '        <div class="photographic_left_sure"></div>\n' +
            '    </div>\n' +
            '    <div class="photographic_body">\n' +
            '        <video autoplay width="1672" height="833"></video>\n' +
            '        <canvas width="1672" height="833"></canvas>\n' +
            '        <img />\n' +
            '    </div>\n' +
            '    <div class="photographic_right">\n' +
            '        <div class="photographic_left_photo"></div>\n' +
            '    </div>\n' +
            '</div>';
        var dialog = $(str);
        options.dialog = dialog;
        $("body").append(dialog);

        //获取页面z-index最大值
        function getMaxZIndex () {
            var maxZ = Math.max.apply(null,
                $.map($('body *'), function(e,n) {
                    if ($(e).css('position') != 'static')
                        return parseInt($(e).css('z-index')) || 1;
                    return 1;
                }));
            return maxZ;
        }

        // 调用权限（打开摄像头功能）
        function getCompetence() {
            dialog.find(".photographic_left_sure").css("display","none");
            dialog.find(".photographic_body").addClass("active");
            dialog.find(".photographic_body img").attr("src","");

            var thisVideo = dialog.find("video").get(0);
            // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
            if (navigator.mediaDevices === undefined) {
                navigator.mediaDevices = {};
            }
            // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
            // 使用getUserMedia，因为它会覆盖现有的属性。
            // 这里，如果缺少getUserMedia属性，就添加它。
            if (navigator.mediaDevices.getUserMedia === undefined) {
                navigator.mediaDevices.getUserMedia = function (constraints) {
                    // 首先获取现存的getUserMedia(如果存在)
                    var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
                    // 有些浏览器不支持，会返回错误信息
                    // 保持接口一致
                    if (!getUserMedia) {
                        return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
                    }
                    // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
                    return new Promise(function (resolve, reject) {
                        getUserMedia.call(navigator, constraints, resolve, reject);
                    })
                }
            }
            var constraints = {
                audio: false,
                // video: {width: $(thisCancas).width(), height: $(thisCancas).height(), transform: 'scaleX(-1)'},
                video: {width: 1672, height: 833}
            };
            navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
                // 旧的浏览器可能没有srcObject
                if ('srcObject' in thisVideo) {
                    thisVideo.srcObject = stream
                } else {
                    // 避免在新的浏览器中使用它，因为它正在被弃用。
                    thisVideo.src = window.URL.createObjectURL(stream)
                }
                thisVideo.onloadedmetadata = function (e) {
                    thisVideo.play()
                }
            }).catch(err => {
                console.log(err)
            })
        }

        // 关闭摄像头
        function stopNavigator() {
            var thisVideo = dialog.find("video").get(0);
            thisVideo.srcObject.forEach(function(track) {
                track.stop();
            });
            thisVideo.srcObject = null;
        }

        //  绘制图片（拍照功能）
        function setImage() {
            var thisCancas = dialog.find("canvas").get(0),
                thisContext = thisCancas.getContext('2d'),
                thisVideo = dialog.find("video").get(0),
                thisImg = dialog.find("img").get(0);

            // 点击，canvas画图
            // thisContext.drawImage(thisVideo, 0, 0, $(thisVideo).width(), $(thisVideo).height());
            thisContext.drawImage(thisVideo, 0, 0,1672, 833);
            // 获取图片base64链接
            var image = thisCancas.toDataURL('image/png');
            thisImg.src = image;

            dialog.find(".photographic_body").addClass("done");
            dialog.find(".photographic_left_sure").css("display","block");
            stopNavigator();
        }

        dialog.on("mouseup touchend",".photographic_left_photo",function () {
            var photographic_body = dialog.find(".photographic_body");
            if(photographic_body.hasClass("done")){
                getCompetence();
                photographic_body.removeClass("done");
            } else if(photographic_body.hasClass("active")) {
                setImage();
                photographic_body.removeClass("active");
            } else {
                getCompetence();
            }
        });
        dialog.on("mouseup touchend",".photographic_left_cancel",function () {
            var photographic_body = dialog.find(".photographic_body");
            if(photographic_body.hasClass("active")){
                stopNavigator();
            }
            dialog.css("display","block");
        });
        dialog.on("mouseup touchend", ".photographic_left_sure",function () {
            //保存图片
        })
    }


    $.fn.photographic = function (options,param) {
        if (typeof options == 'string'){
            return $.fn.photographic.methods[options](this, param);
        }
        options = options || {};
        return this.each(function(){
            var state = $.data(this, 'photographic');
            if (state){
                $.extend(state.options, options);
            } else {
                $.data(this, 'photographic', {
                    options: $.extend({}, $.fn.photographic.defaults, options),
                    photographic: $(this).addClass('photographic')
                });
                init(this);
            }
        });
    };
    $.fn.photographic.methods = {

    };
    $.fn.fileUpload.defaults = {
        //url: "/filestore/item/save", //异步上传
        url: "/filestore/item/upload", //异步上传
        data: null,//数据
        id: 'fileId',
        uploadId: 'mid',
        dialog: null,//拍照弹窗
        params: null,//添加参数
        headers: {},//提交后台抬头
        onStart: null,//上传开始前的执行逻辑
        onProgress: null, //上传进度的回调函数
        onDone: null, //上传完成后的执行逻辑
        onFail: null, //上传失败后的执行逻辑
        onDelete: null,//删除文件前,
        onChange: null,//值改变事件
    };
})(jQuery);